// 收款
import {Row, Col, Button, Space, Form, DatePicker, Upload, message} from 'antd'
import moment from 'moment'
import React, {useEffect, useState} from 'react'
import {useModel, history} from 'umi'
import ReceivablesInfo from '../child/info'
import {FormInput, FormSelect} from '@/components/SearchForm/SearchFormItem'
import page from '../../page.less'
import {getIncomeReceivable, collection} from '@/service/fiance/index'
import {getDict} from '@/service/common/dict'
import {uploadFileUrl} from '@/service/common/upload'
import {twoDecimalPattern} from '@/utils/common/validator'

const formLayout = {
	labelCol: {
		xs: {span: 24},
		sm: {span: 4},
	},
	wrapperCol: {
		xs: {span: 24, offset: 0},
		sm: {span: 12, offset: 0},
	},
}
function ProceedsInfo(props: any) {
	const userID = props
	const {
		query: {id},
	} = userID.location
	const [receivableInformation, setReceivableInformation] = useState<any>({
		plateNo: '',
		receivableNo: '',
		driverName: '',
		lessorName: '',
		collectionTypename: '',
		paymentMethodname: '',
		rentTypename: '',
		stage: '',
		receivableTime: '',
		overdueDays: '',
		payStatus: '',
		payStatusname: '',
		logListDtoList: [],
		receivableAmount: '',
		receivedAmount: '',
		abatementAmount: '',
		exemptionAmount: '',
		uncollectedAmount: '',
		receivableStartTime: '',
		collectionType: '',
	}) // 应收单信息
	// const [operationRecord,setOperationRecord] = useState([])
	const getList = () => {
		getIncomeReceivable(id).then((res) => {
			const data = {...res?.data}
			data.overdueDays = moment(data?.collectionTime).diff(
				moment(data?.receivableTime),
				'days',
			)
			setReceivableInformation(data)
			// setOperationRecord(data?.logListDtoList)
		})
	}
	const [dict, setDict] = useState({
		order_finance_pey_type: [],
	}) // 字典值
	useEffect(() => {
		getList()
		getDict(
			{
				dictKeys: [
					'order_finance_pey_type', // 付款方式
				],
			},
			(res: any) => {
				setDict(res)
			},
		)
	}, [])
	const receivableInfo = [
		{label: '车牌号', value: receivableInformation?.plateNo},
		{label: '应收单号', value: receivableInformation?.receivableNo},
		{label: '司机名称', value: receivableInformation?.driverName},
		{label: '所属公司', value: receivableInformation?.lessorName},
		{label: '收款类型', value: receivableInformation?.collectionTypename},
		{label: '付款方式', value: receivableInformation?.paymentMethodname},
		// { label: '租赁类型', value: receivableInformation?.rentTypename },
		// { label: '账单期数', value: receivableInformation?.stage },
		// { label: '应收日期', value: receivableInformation?.receivableTime },
		// { label: '逾期天数', value: receivableInformation?.overdueDays },
	]

	// 费用明细
	const expenseDetails = [
		{label: '应收费用', value: receivableInformation?.receivableAmount},
		{label: '已收费用', value: receivableInformation?.receivedAmount},
		{label: '费用减免金额', value: receivableInformation?.abatementAmount},
		{label: '免租金额', value: receivableInformation?.exemptionAmount},
		{label: '待收', value: receivableInformation?.uncollectedAmount},
	]
	// 定金费用明细
	const depositExpenseDetails = [
		{label: '应收费用', value: receivableInformation?.receivableAmount},
		{label: '已收费用', value: receivableInformation?.receivedAmount},
		{label: '待收', value: receivableInformation?.uncollectedAmount},
	]
	// 原订单押金
	const oldDeposit = [
		{
			label: '应收费用',
			value: (
				Number(receivableInformation?.totalAmount) -
				Number(receivableInformation?.receivableAmount)
			).toFixed(2),
		},
		{
			label: '已收费用',
			value: (
				Number(receivableInformation?.totalAmount) -
				Number(receivableInformation?.receivableAmount)
			).toFixed(2),
		},
	]
	// 续签订单押金
	const continuedDeposit = [
		{label: '应收费用', value: receivableInformation?.totalAmount},
	]
	// 原订单押金
	const repairDeposit = [
		{label: '应收费用', value: receivableInformation?.receivableAmount},
		{label: '已收费用', value: receivableInformation?.receivedAmount},
		{label: '待收', value: receivableInformation?.uncollectedAmount},
	]
	const [form] = Form.useForm()
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [oldFileList, setOldFileList] = useState<any>([]) // 原车上传验车清单
	const [btnStatus, setBtnStatus] = useState(0)
	const [payType, setPayType] = useState()
	const [statue1, setStatue1] = useState(1)
	const [statue2, setStatue2] = useState(1)
	const [statue3, setStatue3] = useState(1)
	useEffect(() => {
		// 定金只有3项 ，其余的5项
		if (receivableInformation?.collectionType === '1') {
			setStatue1(2)
			setStatue2(1)
			setStatue3(1)
		} else {
			setStatue1(1)
			setStatue2(1)
			setStatue3(2)
		}
		// 押金续签会产生原订单
		if (
			receivableInformation?.collectionType === '2' &&
			receivableInformation?.renewLeaseStatus === 2
		) {
			setStatue1(1)
			setStatue2(2)
			setStatue3(1)
		} else if (
			receivableInformation?.collectionType === '2' &&
			receivableInformation?.renewLeaseStatus === 1
		) {
			setStatue1(2)
			setStatue2(1)
			setStatue3(1)
		}
	})
	//  文件上传生成上传信息-上传原车验车清单
	const uploadPropsOld = {
		action: uploadFileUrl,
		name: fileName, // 滴滴上传:file 测试上传:files
		data: {
			modelName: 'receivables',
			targetAttr: 1,
		},
		beforeUpload: (file: any) => {
			const isLt200M = file.size / 1024 / 1024 < 200
			if (!isLt200M) {
				message.error('文件必须小于200MB')
			}
			return isLt200M
		},
		onChange(info: any) {
			if (info.file.status === 'done') {
				setOldFileList(info?.fileList)
				const list: any = []
				info?.fileList?.map((res: any) =>
					list.push(res?.response?.data?.id?.toString()),
				)
				form.setFieldsValue({urlList: list})
			}
			setOldFileList(info?.fileList)
		},
		oldFileList,
	}
	// 获取当前时间
	const nowTime = () => {
		setBtnStatus(1)
		const time = moment().locale('zh-cn').format('YYYY-MM-DD HH:mm:ss')
		form.setFieldValue('collectionTime', time)
	}
	// 获取应收时间
	const receivableTime = () => {
		setBtnStatus(2)
		form.setFieldValue(
			'collectionTime',
			receivableInformation?.receivableTime,
		)
	}
	// 支付类型更变
	const typeChange = (_text: any, option: any) => {
		setPayType(option?.dictValue)
	}
	// 时间选择
	const datePickerChange = (value: any, dateString: string) => {
		setBtnStatus(3)
		form.setFieldValue('collectionTime', dateString)
	}
	// 提交
	const onFinish = () => {
		const data = form.getFieldsValue()
		const param = {
			receivableId: id,
			peyTypename: payType,
		}
		collection({...data, ...param}).then((res) => {
			if (res?.success) {
				message.success(res?.msg)
				history.push({
					pathname: '/finance/accountsReceivable',
				})
			}
		})
	}

	return (
		<div className={page.page}>
			<ReceivablesInfo
				title="应收单信息"
				info={receivableInfo}
				span={8}
				state={{
					label: '支付状态',
					value: receivableInformation?.payStatusname,
				}}
			/>
			{statue1 === 2 && (
				<ReceivablesInfo
					title="费用明细"
					info={depositExpenseDetails}
					span={8}
					state={{label: '', value: ''}}
				/>
			)}
			{statue2 === 2 && (
				<>
					<ReceivablesInfo
						title="原订单押金费用明细"
						info={oldDeposit}
						span={8}
						state={{label: '', value: ''}}
					/>
					<ReceivablesInfo
						title="续签押金费用明细"
						info={continuedDeposit}
						span={8}
						state={{label: '', value: ''}}
					/>
					<ReceivablesInfo
						title="需要补缴押金费用明细"
						info={repairDeposit}
						span={8}
						state={{label: '', value: ''}}
					/>
				</>
			)}
			{statue3 === 2 && (
				<ReceivablesInfo
					title="费用明细"
					info={expenseDetails}
					span={8}
					state={{label: '', value: ''}}
				/>
			)}
			<div className={page.page}>
				<div className={page.card}>
					<p className={page.dotTitle}>收款操作</p>
					<Form
						form={form}
						name="basic"
						onFinish={onFinish}
						onFinishFailed={() => {}}
						autoComplete="off"
						{...formLayout}
						wrapperCol={{flex: 1}}>
						<Row gutter={24}>
							<Col span={24}>
								<FormInput
									name="actualAmount"
									label="实际收款"
									rules={[
										{
											required: true,
											pattern: twoDecimalPattern,
											message:
												'请填写数字，只支持小数点后俩位',
										},
									]}
									style={{width: '300px'}}
									placeholder="请填写实际收款金额"
								/>
							</Col>
							<Col span={24}>
								<Form.Item
									name="collectionTime"
									label="收款时间"
									rules={[
										{
											required: true,
											message: '请设置收款时间',
										},
									]}>
									<Space>
										<Button
											onClick={nowTime}
											className={
												btnStatus === 1
													? page.btnStyle
													: ''
											}>
											当前时间
										</Button>
										<Button
											onClick={receivableTime}
											className={
												btnStatus === 2
													? page.btnStyle
													: ''
											}>
											应收时间
										</Button>
										<DatePicker
											placeholder="其他时间"
											style={{width: '180px'}}
											onChange={datePickerChange}
											format="YYYY-MM-DD HH:mm:ss"
										/>
									</Space>
								</Form.Item>
							</Col>
							<Col span={24}>
								<FormInput
									name="transactionNo"
									label="付款流水号"
									rules={[
										{
											required: true,
											message:
												'请输入付款流水号，多个用“，”隔开',
										},
									]}
									style={{width: '300px'}}
									placeholder="请输入付款流水号，多个用“，”隔开"
								/>
							</Col>
							<Col span={24}>
								<FormSelect
									label="支付类型"
									placeholder="请选择支付类型"
									name="peyType"
									rules={[
										{
											required: true,
											message: '请选择支付类型',
										},
									]}
									style={{width: '300px'}}
									keys="dictKey"
									title="dictValue"
									items={dict?.order_finance_pey_type}
									onChange={typeChange}
								/>
							</Col>
							<Col span={24}>
								<FormInput
									name="remark"
									label="备注"
									style={{width: '600px'}}
									placeholder="请填写收款备注，不超过200个字符"
									rules={[
										{
											max: 200,
											message: '备注不得超过200个字符',
										},
									]}
								/>
							</Col>
							<Col span={24}>
								<Form.Item name="urlList" label="收款附件">
									<Upload {...uploadPropsOld}>
										{oldFileList?.length >= 5 ? null : (
											<Button>添加附件</Button>
										)}
									</Upload>
									<p style={{margin: '15px 0 0 0'}}>
										附件说明：附件最大支持200M，
									</p>
									<p>支持格式：PDF、Word、Excel、JPG、PNG</p>
								</Form.Item>
							</Col>
						</Row>
						<Row justify="center" style={{marginTop: '20px'}}>
							<Form.Item>
								<Space>
									<Button
										shape="round"
										onClick={() => {
											history.goBack()
										}}>
										取消
									</Button>
									<Button
										shape="round"
										type="primary"
										htmlType="submit">
										提交
									</Button>
								</Space>
							</Form.Item>
						</Row>
					</Form>
				</div>
			</div>
		</div>
	)
}
export default ProceedsInfo
